#!/bin/bash

# 生产环境快速修复脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

PROJECT_DIR=$(dirname "$(readlink -f "$0")")

log_info "开始生产环境修复..."

# 确保在项目根目录
cd "$PROJECT_DIR"
log_info "当前目录: $(pwd)"

# 激活虚拟环境
if [ -d "yxyweb_venv" ]; then
    source yxyweb_venv/bin/activate
    log_info "已激活虚拟环境"
else
    log_error "虚拟环境不存在"
    exit 1
fi

# 设置环境变量
export PYTHONPATH="$PROJECT_DIR:$PYTHONPATH"
log_info "已设置Python路径"

# 运行诊断
log_info "运行生产环境诊断..."
python3 diagnose_production.py

# 如果诊断发现问题，尝试修复
log_info "尝试修复file.py模块..."

# 创建一个简化的file.py
cat > db/models/file_simple.py << 'EOF'
from sqlalchemy import Column, Integer, String, DateTime, JSON, Text, ForeignKey, BigInteger, Float
from sqlalchemy.orm import relationship
from datetime import datetime

# 直接导入Base，避免循环导入
from db.models.base import Base

class FileUpload(Base):
    """文件上传表"""
    __tablename__ = "file_uploads"
    __table_args__ = {'extend_existing': True}

    id = Column(Integer, primary_key=True, autoincrement=True, index=True)
    file_id = Column(String(50), unique=True, nullable=False, index=True)
    user_id = Column(String(100), nullable=False, index=True)
    file_name = Column(String(255), nullable=False)
    file_size = Column(BigInteger, nullable=False)
    file_path = Column(String(500), nullable=False)
    file_hash = Column(String(64), nullable=False)
    file_type = Column(String(50), nullable=False)
    knowledge_base = Column(String(100), nullable=True)
    status = Column(String(50), default="uploaded", nullable=False)
    upload_progress = Column(Integer, default=0)
    uploaded_bytes = Column(BigInteger, default=0)
    upload_speed = Column(BigInteger, default=0)
    estimated_time = Column(Float, default=0)
    upload_time = Column(DateTime, default=datetime.utcnow)
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    # 关系映射
    analysis_results = relationship('FileAnalysisResult', back_populates='file')

class FileAnalysisResult(Base):
    """文件分析结果表"""
    __tablename__ = "file_analysis_results"
    __table_args__ = {'extend_existing': True}

    id = Column(Integer, primary_key=True, autoincrement=True, index=True)
    file_id = Column(String(50), ForeignKey('file_uploads.file_id'), nullable=False)
    analysis_type = Column(String(50), nullable=False)
    analysis_status = Column(String(50), default="pending", nullable=False)
    analysis_progress = Column(Integer, default=0)
    current_step = Column(String(100), nullable=True)
    step_progress = Column(Integer, default=0)
    analysis_options = Column(JSON, nullable=True)
    analysis_result = Column(JSON, nullable=True)
    error_message = Column(Text, nullable=True)
    analysis_start_time = Column(DateTime, nullable=True)
    analysis_end_time = Column(DateTime, nullable=True)
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    # 关系映射
    file = relationship('FileUpload', back_populates='analysis_results')
EOF

# 备份原文件并替换
if [ -f "db/models/file.py" ]; then
    mv db/models/file.py db/models/file.py.backup
    log_info "已备份原file.py文件"
fi

mv db/models/file_simple.py db/models/file.py
log_info "已替换为简化的file.py"

# 测试修复结果
log_info "测试修复结果..."
python3 -c "
import sys
sys.path.insert(0, '.')
try:
    from db.models.file import FileUpload, FileAnalysisResult
    print('✅ file.py模块导入成功')
except Exception as e:
    print(f'❌ file.py模块导入失败: {e}')
    import traceback
    traceback.print_exc()
"

log_success "修复完成！现在尝试启动服务："
echo "  ./start.sh"
